package public

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var db *gorm.DB

// 模型
type Album struct {
	ID     uint `gorm:"primaryKey"`
	Title  string
	Artist string
	Price  float64
}

// 指定表名，GORM默认把数据库增加s，变成albums，所以需要指定表名，变回album
func (Album) TableName() string {
	return "album"
}

func initDBs() {
	dsn := "root:root@tcp(127.0.0.1:3306)/recordings?charset=utf8mb4&parseTime=True&loc=Local"
	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("连接数据库失败: " + err.Error())
	} else {
		fmt.Println("连接成功")
	}
}

func GetIndexProducts(c *gin.Context) {
	initDBs()

	// 查询
	var a, b Album

	db.First(&a)
	fmt.Println("查询结果：", a)

	db.First(&b, 5)
	fmt.Println("查询结果：", b)

	c.JSON(200, gin.H{
		"first":  a,
		"second": b,
	})
}
